package com.alibaba.algo.aop;

import com.alibaba.algo.core.base.BaseEntity;
import com.xxl.sso.core.user.XxlSsoUser;
import com.alibaba.algo.utils.UserContextUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;

/**
 * @ClassName: CurrentUserAop
 * @Description: 登录用户aop, 用于统一设置BaseEntity中的创建人和修改人
 * @Author: wugongzi
 * @Date: 2021/12/02 16:07
 * @Version: 1.0
 */
@Configuration
@Aspect
@Order(2)
public class CurrentUserAop {

    private static final Logger logger = LoggerFactory.getLogger(CurrentUserAop.class);

//    private ThreadLocal<XxlSsoUser> currentUserThreadLocal = new ThreadLocal<>();
    /**
     * 切入点
     */
    @Pointcut("execution(* com.alibaba.algo.core.base.BaseDomain.insert*(..)) || execution(* com.alibaba.algo.core.base.BaseDomain.update*(..))")
    public void pointcut() {

    }

    /**
     * 前置增强
     *
     * @param joinPoint
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        logger.info("=====CurrentUserAop start=====");
        // 获取当前登录用户
//        XxlSsoUser currentUser = currentUserThreadLocal.get();
//        if(ObjectUtils.isEmpty(currentUser)){
        String userName = UserContextUtils.getCurrentUserName();
//        }
        if (!ObjectUtils.isEmpty(userName)) {
//            currentUserThreadLocal.set(currentUser);
            // 获取切入点方法
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            String methodName = method.getName();
            // 获取切入点参数
            Object[] args = joinPoint.getArgs();
            BaseEntity baseEntity = null;
            for (Object arg : args) {
                if (arg instanceof BaseEntity) {
                    baseEntity = (BaseEntity) arg;
                }
            }
            if (!ObjectUtils.isEmpty(baseEntity)) {
                //insert/insertWithID新增方法设置创建人，updateById修改方法设置修改人
                if ("insert".equals(methodName) || "insertWithID".equals(methodName)) {
                    baseEntity.setCreator(userName);
                } else if ("updateById".equals(methodName)) {
                    baseEntity.setModifier(userName);
                }
            }
        } else {
            logger.info("currentUser is empty");
        }
        logger.info("=====CurrentUserAop end=====");
    }

}
